//
//  NovelDetailsViewController.m
//  A_Program
//
//  Created by dlios on 15-5-22.
//  Copyright (c) 2015年 BayMax. All rights reserved.
//

#import "NovelDetailsViewController.h"
#import "NovelDetailsHeaderView.h"
#import "NovelDetailsTableViewCell.h"
#import "SANetWorkingTask.h"
#import "NovelSecondModel.h"
#import "NovelDetailsModel.h"
#import "NovelAlbumViewController.h"
#import "MJRefresh.h"
#import "ConnectModel.h"
#import "NovelModel.h"
#import "NovelDatabase.h"
#import "LoginNextViewController.h"

@interface NovelDetailsViewController ()<NovelDetailHeaderViewDelegate,UITableViewDelegate,UITableViewDataSource,MyCollectButtonDelegate>

@end

@implementation NovelDetailsViewController
- (void)dealloc
{
    [self.namePath release];
    [self.detailsPath release];
    [self.array release];
    [self.detailsFristArray release];
    [self.detailesFristTableView release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if ( self) {
         self.array  = [NSMutableArray array];
       self.detailsFristArray = [NSMutableArray array];
        self.detailsPageCount = 2;
        
    }
    return self;
    
   
}
- (void)loadView{
    [super loadView];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.view setBackgroundColor:[UIColor colorWithWhite:1 alpha:0.9]];
    [self createSegmentView];
    [self createMakeDetailsTableView];
    self.detailsPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=book&condition=hot&device=android&page=1&per_page=20&status=0&tag_name=%@",self.namePath];
    if ([self isConnectionAvailable:0]) {
        [self createDetailsDate:self.detailsPath];
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //收藏按钮协议
  
}
- (void)createDetailsDate:(NSString *)detailsDate{
    //1.请求数据
    
    [SANetWorkingTask request:detailsDate parmater:nil block:^(NSDictionary *result) {

        NSMutableArray *fristArray = [result objectForKey:@"list"];
        if (fristArray.count == 0) {
            [self.detailesFristTableView removeFooter];
            return;
        }
        for (NSMutableDictionary *myDic in fristArray) {
            NovelDetailsModel *detailsModel = [[[NovelDetailsModel alloc]init]autorelease];
            [detailsModel setValuesForKeysWithDictionary:myDic];
            [self.array addObject:detailsModel];
            
        }
        self.detailsFristArray = [NSMutableArray arrayWithArray:self.array];
        [self.detailesFristTableView reloadData];
    }];
    

}


//建立头部View
- (void)createSegmentView{
    //头部view
    NovelDetailsHeaderView *detailsHeaderView = [[NovelDetailsHeaderView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height*0.05+20)];
    //建立代理
    detailsHeaderView.detailDelegate = self;
    [self.view addSubview:detailsHeaderView];
    [detailsHeaderView release];
}
//建立tableView
- (void)createMakeDetailsTableView{
    self.detailesFristTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,[UIScreen mainScreen].bounds.size.height*0.05+20, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height*0.752)];
    //加入子视图tableView
    [self.view addSubview:self.detailesFristTableView];
    self.detailesFristTableView.delegate = self;
    self.detailesFristTableView.dataSource = self;
    //建立下拉刷新上拉加载
    [self.detailesFristTableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadNewData:)];
    [self.detailesFristTableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.detailesFristTableView release];
}
//判断网络使用
-(BOOL) isConnectionAvailable:(NSInteger)count{
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            NSLog(@"没网");
            if (count == 1) {
                [self.detailesFristTableView.header endRefreshing];
            }else if(count == 2){
                [self.detailesFristTableView.footer endRefreshing];
            }
            
            [self alertView:@"没有网络连接"];
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            NSLog(@"用的WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            NSLog(@"3G");
            [self alertView:@"使用3G连接"];
            break;
    }
    
    
    return isExistenceNetwork;
}
// 警告框
- (void)alertView:(NSString *)str
{
    UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
    [alert setDelegate:self];
    [alert show];
    [alert release];
    
}

#pragma mark-
#pragma 下拉刷新
//下拉刷新点击事件
- (void)loadNewData:(id)sender
{
    if ([self isConnectionAvailable:1]) {
        [self.detailesFristTableView reloadData];
        [self.detailesFristTableView.header endRefreshing];

    }
    
   }
//上拉加载点击事件
- (void)loadMoreData{
    if ([self isConnectionAvailable:2]) {
        if (self.segment.selectedSegmentIndex == 0) {
            self.detailsPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=book&condition=hot&device=android&page=%ld&per_page=20&status=0&tag_name=%@",self.detailsPageCount,self.namePath];
            [self createDetailsDate:self.detailsPath];
            
            
        }else if(self.segment.selectedSegmentIndex == 1){
            self.detailsPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=book&condition=recent&device=android&page=%ld&per_page=20&status=0&tag_name=%@",self.detailsPageCount,self.namePath];
            [self createDetailsDate:self.detailsPath];
            
            
        }else if(self.segment.selectedSegmentIndex == 2){
            self.detailsPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=book&condition=classic&device=android&page=%ld&per_page=20&status=0&tag_name=%@",self.detailsPageCount,self.namePath];
            [self createDetailsDate:self.detailsPath];
            
            
        }
        
        // 拿到当前的上拉刷新控件，结束刷新状态
        self.detailsPageCount += 1;
        [self.detailesFristTableView.footer endRefreshing];
    }
    
    
}

//tableView协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.detailsFristArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cella = @"cell";
    static NSString *cellb = @"cell1";
    static NSString *cellc = @"cell2";
    if (self.segment.selectedSegmentIndex == 0) {
        NovelDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cella];
        if (!cell) {
            cell = [[[NovelDetailsTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cella]autorelease];
        }
        NovelDetailsModel *detailsModel = [self.detailsFristArray objectAtIndex:indexPath.row];
        [cell createDetailsTableViewCell:detailsModel];
        //按钮协议
        cell.collectDelegate = self;
        
        return cell;
        
    }else if (self.segment.selectedSegmentIndex == 1){
        NovelDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellb];
        if (!cell) {
            cell = [[[NovelDetailsTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellb]autorelease];
        }
        NovelDetailsModel *detailsModel = [self.detailsFristArray objectAtIndex:indexPath.row];
        [cell createDetailsTableViewCell:detailsModel];
        //按钮协议
        cell.collectDelegate = self;

        return cell;

    }else if (self.segment.selectedSegmentIndex == 2){
        NovelDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellc];
        if (!cell) {
            cell = [[[NovelDetailsTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellc]autorelease];
        }
        NovelDetailsModel *detailsModel = [self.detailsFristArray objectAtIndex:indexPath.row];
        [cell createDetailsTableViewCell:detailsModel];
        //按钮协议
        cell.collectDelegate = self;
        
        return cell;

    }
    return nil;
   }
//高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return ([UIScreen mainScreen].bounds.size.height - 10)/6;
}
//跳转
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NovelAlbumViewController *albumView = [[NovelAlbumViewController alloc]init];
    NovelDetailsModel *detailModel = [self.detailsFristArray objectAtIndex:indexPath.row];
    albumView.publicPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/1/15",detailModel.myId];
    albumView.albumId = detailModel.myId;
    [self.detailesFristTableView deselectRowAtIndexPath:indexPath animated:YES];
 
    [self.navigationController pushViewController:albumView animated:YES];
    [albumView release];
}



//实现代理
- (void)createSegment:(id)sender{
    UISegmentedControl *segment = (UISegmentedControl *)sender;
    switch (segment.selectedSegmentIndex) {
        case 0:
        {
            self.detailsPageCount = 1;
            [self.array removeAllObjects];
            [self.detailsFristArray removeAllObjects];
            self.detailsPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=book&condition=hot&device=android&page=1&per_page=20&status=0&tag_name=%@",self.namePath];
            [self createDetailsDate:self.detailsPath];
            
    
        }
            break;
        case 1:
        {
            self.detailsPageCount = 1;
            [self.array removeAllObjects];
            [self.detailsFristArray removeAllObjects];
            self.detailsPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=book&condition=recent&device=android&page=1&per_page=20&status=0&tag_name=%@",self.namePath];
            [self createDetailsDate:self.detailsPath];

        }
            break;
        case 2:
        {
            self.detailsPageCount = 1;
            [self.array removeAllObjects];
            [self.detailsFristArray removeAllObjects];
            self.detailsPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=book&condition=classic&device=android&page=1&per_page=20&status=0&tag_name=%@",self.namePath];
            [self createDetailsDate:self.detailsPath];
            
        }
            break;
        default:
            break;
    }
    
}
//收藏按钮的db传数据
- (void)createCollectAction:(NSString *)collect{
    NSUserDefaults *myLoginName = [[NSUserDefaults alloc]init];
                NSString *collectStr = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/1/15",collect];
                [ConnectModel connectWithUrl:collectStr block:^(NSData *data) {
                    self.novelModel = [[NovelModel alloc]init];
                    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    NSMutableDictionary *myHeaderDic = [dic objectForKey:@"album"];
                    [self.novelModel setValuesForKeysWithDictionary:myHeaderDic];
                    //读取userDefault的信息
                    self.novelModel.loginName = [myLoginName objectForKey:@"loginName"];
                    self.novelModel.playKind = @"novel";
                    self.novelModel.albumIdMin = [collect integerValue];
                    [NovelDatabase insertWithModel:self.novelModel];
                }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
